﻿using System;
using System.Linq;
using System.Linq.Expressions;
using ASPItalia.ModelVirtualCasting.Common;
using ASPItalia.ModelVirtualCasting.ObjectModel;

namespace ASPItalia.ModelVirtualCasting.EntityFramework
{
	public class NewsRepository : BaseRepository<News>, INewsRepository
	{
		public NewsRepository(IContextContainer container) : base(container)
		{
		}

		public void InsertOnSubmit(News entity)
		{
			Context.News.AddObject(entity);
		}

		public void Update(News entity)
		{
			Context.News.Attach(entity);
			Context.ObjectStateManager.GetObjectStateEntry(entity).SetModified();
		}

		public void DeleteOnSubmit(News entity)
		{
			Context.News.DeleteObject(entity);
		}

		public void SubmitChanges()
		{
			SaveChanges();
		}

		public IQueryable<News> GetLastNews(int number)
		{
			return CurrentObjectQuery.OrderBy(n => n.NewsDate).Take(number);
		}

		public IQueryable<News> GetAll()
		{
			return CurrentObjectQuery;
		}

		public IQueryable<News> Where(Expression<Func<News, bool>> predicate)
		{
			return CurrentObjectQuery.Where(predicate);
		}

		public long Count(Expression<Func<News, bool>> predicate)
		{
			return CurrentObjectQuery.Count(predicate);
		}

		public News GetByID(int id)
		{
			return CurrentObjectQuery.First(n => n.NewsID == id);
		}

		public INewsRepository Include(params string[] paths)
		{
			CurrentObjectQuery = CreateObjectQuery().Include(paths);
			return this;
		}

		#region IReadOnlyRepository<INewsRepository,News> Members


		public INewsRepository EnableLazyLoading()
		{
			SetLazyLoading(true);
			return this;
		}

		public INewsRepository DisableLazyLoading()
		{
			SetLazyLoading(false);
			return this;
		}

		#endregion
	}
}